/*
 * To change this license header, choose License Headers in Project Properties.
 * To change this template file, choose Tools | Templates
 * and open the template in the editor.
 */

package jsf;

import static com.sun.faces.facelets.util.Path.context;
import entities.Prodotto;
import java.io.Serializable;
import java.util.ArrayList;
import java.util.List;
import java.util.logging.Level;
import java.util.logging.Logger;
import javax.ejb.EJB;
import javax.enterprise.context.SessionScoped;
import javax.faces.context.FacesContext;
import javax.inject.Named;
import session.OrderManagerLocal;
import session.exceptions.OrderException;

/**
 *
 * @author sflesca
 */
@Named(value = "carrelloManagedBean")
@SessionScoped
public class CarrelloManagedBean implements Serializable {
    @EJB
    private OrderManagerLocal orderManager;
    
    private List<Prodotto> prodotti = new ArrayList<Prodotto>();

    /**
     * Creates a new instance of CarrelloManagedBean
     */
    public CarrelloManagedBean() {
    }

    public List<Prodotto> getProdotti() {
        return prodotti;
    }

    public void setProdotti(List<Prodotto> prodotti) {
        this.prodotti = prodotti;
    }
    
    public int getItemCount(){
        return prodotti.size();
    }
    
    public void add(Prodotto prodotto) {
        if(!(prodotti.contains(prodotto)))
            prodotti.add(prodotto);
    }
    
    public String ordina(){
        try {
            FacesContext context = FacesContext.getCurrentInstance();
            LoginManagerManagedBean lm = (LoginManagerManagedBean) context.getApplication().evaluateExpressionGet(context, "#{loginManager}", LoginManagerManagedBean.class);
            orderManager.creaOrdine(lm.getClienteCorrente(), prodotti);
            prodotti.clear();
            return "ordinato";
        } catch (OrderException ex) {
            Logger.getLogger(CarrelloManagedBean.class.getName()).log(Level.SEVERE, null, ex);
            return "erroreOrdine";
        }
    }
}
